<?php
/**
 * tmaic.com 
 * ============================================================================
 * * 版权所有 2020-2030 tmaic，并保留所有权利。
 * 网站地址: http://www.tmaic.com；
 * ----------------------------------------------------------------------------
 * 这不是一个自由软件！您只能在不用于商业目的的前提下对程序代码进行修改和
 * 使用；不允许对程序代码以任何形式任何目的的再发布。
 * ============================================================================
 * $Author: pangxianfei
 * $email:421339244@qq.com
 * $phone:18929142226
 * $date 2020-11-13
*/
namespace App\Http\Controllers\Admin;


use Illuminate\Http\Request;
use App\Http\Controllers\AdminController;
use EasyWeChat\Factory;
use App\Models\Refund\Refund;
use App\Models\Refund\Log;
use App\Models\Order\Order;
use App\Models\Order\Goods;
use Illuminate\Support\Facades\DB;

class RefundController extends AdminController
{
    protected $app;
    protected $config;
    protected $jssdk;
    /**
     * Create a new AdminController instance.
     *
     * @return void
     */
    public function __construct()
    {

        $this->config = config('wechat.payment.default');
        $this->app = Factory::payment($this->config);
        $this->jssdk = $this->app->jssdk;

    }

    public function index(Request $request)
    {
        $Refund = Refund::paginate($request->get('limit', 8));
        return view('admin.refund.index', compact('Refund'));
    }

    public function data(Request $request)
    {

        $username = $request->get('username') ?? null;
        $phone = $request->get('phone') ?? null;
        $created_at = $request->get('created_at') ?? null;
        $model = Refund::query();
        $model = $model->leftJoin('member', 'refund.uid', '=', 'member.id');
        if ($request->get('order_no')) {
            $model = $model->where('refund.order_no', 'like', '%' . $request->get('order_no') . '%');
        }

        if ($request->get('status')) {
            $status = $request->get('status');
            switch ($request->get('status')) {
                case "1":
                    $model = $model->where('refund_status', 1);
                    break; //已退款
                case "2":
                    $model = $model->where('refund_status', 2);
                    break; //未退款
                case "3":
                    $model = $model->where('refund_status', 3);
                    break; //拒绝
               case "4":
                    $model = $model->where('refund_status', 4);
                    break; //完成
            }
        }


        if (!empty($username)) {
            $model = $model->where('member.username', 'like', "%{$username}%");
        }

        if (!empty($phone)) {
            $model = $model->where('member.moblie', 'like', "%{$phone}%");
        }
        if (!empty($created_at)) {
            $startime = substr($created_at, 0, 20);
            $endtime = substr($created_at, -20, 20);
            $model = $model->whereBetween('refund.created_at', [$startime, $endtime]);
        }
        $res = $model->with(['user', 'order'])->orderBy('refund.rid', 'desc')->paginate(8);//$request->get('limit', 8)
        $data = [
            'code' => 0,
            'msg' => '正在请求中...',
            'count' => $res->total(),
            'data' => $res->items()
        ];
        return response()->json($data);
    }

    public function goodsData(Request $request)
    {
        $model = Goods::query();
        if ($request->get('id')) {
            $model = $model->where('order_id', $request->get('id'));
        }
        $res = $model->orderBy('id', 'asc')->paginate($request->get('limit', 10));
        $data = [
            'code' => 0,
            'msg' => '正在请求中...',
            'count' => $res['total'],
            'data' => $res->items()
        ];
        return response()->json($data);
    }

    

    public function execute(Request $request)
    {
        $ids = $request->get('ids');

        $refund = Refund::with('goods')->find($ids);
        // 参数分别为：微信订单号、商户退款单号、订单金额、退款金额、其他参数
        $msg =  $this->app->refund->byTransactionId($refund->out_trade_no,$refund->refund_no, $refund->total_money*100, $refund->refund_fee*100, $config = []);

        DB::beginTransaction();
        try {

            //修改退款状态
            $refundData['refund_status'] = 4;
            $refundStatus = $refund->update($refundData);
            //修改订单状态
            $orderUpdate['refund_status'] = 0;
            $orderUpdate['order_status_action'] = '退款完成';
            $orderUStatus = Order::where(['order_no'=>$refund->order_no,'out_trade_no'=>$refund->out_trade_no])->update($orderUpdate);

           

           if($orderUStatus && $refundStatus && $msg['return_code']=="SUCCESS" && $msg['result_code'] == "SUCCESS"){

                if ($refund){
                    foreach ($refund->goods as $child) {
                        $data[] = [
                            'refundid'=>$refund->rid,
                            'refund_status'=>4,
                            'updated_at'=>now(),
                            'created_at'=>now(),
                        ];
                    }
                    $refund->LogData()->insert($data);
                }
                DB::commit();
                return $this->success('退款申请接收成功');
          }  
        } catch (\Exception $exception) {
            DB::rollback();
        }

        return $this->error('退款申请接收失败!');
    }


    /**
     * Remove the specified resource from storage.
     *
     * @param int $id
     * @return \Illuminate\Http\Response
     */
    public function destroy(Request $request)
    {
        $ids = $request->get('ids');
        return response()->json(['code' => 1, 'msg' => '删除失败']);
         
        if (empty($ids)) {
            return response()->json(['code' => 1, 'msg' => '请选择删除项']);
        }
        if (Refund::destroy($ids)) {
            return response()->json(['code' => 0, 'msg' => '删除成功']);
        }
        return response()->json(['code' => 1, 'msg' => '删除失败']);
    }


}
